/*
*@Name: 母婴商城
*@Author: xuzhiwen
*@Copyright:layui.com
*/

layui.define(['jquery','layer'],function(exports){
	var layer = layui.layer;$ = layui.$;
	
var car = {
  init : function(){
  		var uls = document.getElementById('list-cont').getElementsByTagName('ul');//每一行
  		var checkInputs = document.getElementsByClassName('check'); // 所有勾选框
      var checkAll = document.getElementsByClassName('check-all'); //全选框
      var SelectedPieces = document.getElementsByClassName('Selected-pieces')[0];//总件数
      var piecesTotal = document.getElementsByClassName('pieces-total')[0];//总价
      var batchdeletion = document.getElementsByClassName('batch-deletion')[0]//批量删除按钮
      //计算
      var ids='';
      function getTotal(){
          var arr=[];
          var seleted = 0,price = 0;
          for(var i = 0; i < uls.length;i++){
                if(uls[i].getElementsByTagName('input')[0].checked){
                seleted += parseInt(uls[i].getElementsByClassName('Quantity-input')[0].value);
                price += parseFloat(uls[i].getElementsByClassName('sum')[0].innerHTML);
                    tmp = parseInt(uls[i].getElementsByClassName('CheckBoxShop')[0].value);

                    arr.push(tmp);

              }
      		}

          ids = arr.join(',')
          // console.log(ids);
          SelectedPieces.innerHTML = seleted;
          piecesTotal.innerHTML = '￥' + price.toFixed(2);
          // console.log(seleted)
      }

      $(".jiesuan").click(function () {
          console.log(ids);
          $.ajax({
              type:"get",
              url:"/order/create",
              data:{'ids':ids},
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              },
              success:function(res) {
                  data = JSON.parse(res)

                  if(data.code==200){
                      layer.msg(data.msg);
                      window.location="/order/"+data.msg+"/edit";
                  }else {
                      layer.msg(data.msg, {icon: 2, time: 1500}, );
                  }
              },
              error:function(data) {
                  console.log('err');
              }
          });
      })

      // 小计
      function getSubTotal(ul){
        var unitprice = parseFloat(ul.getElementsByClassName('th-su')[0].innerHTML);
        var count = parseInt(ul.getElementsByClassName('Quantity-input')[0].value);
        var SubTotal = parseFloat(unitprice*count)
        ul.getElementsByClassName('sum')[0].innerHTML = SubTotal.toFixed(2);
      }

      for(var i = 0;i < checkInputs.length;i++){
        checkInputs[i].onclick = function(){
          if(this.className === 'check-all check'){
            for(var j = 0;j < checkInputs.length; j++){
              checkInputs[j].checked = this.checked;
            }
          }
          if(this.checked == false){
            for(var k = 0;k < checkAll.length;k++){
              checkAll[k].checked = false;
            }
          }
          getTotal()
        }

      }

      function updateCars(id,num) {
          $.ajax({
              type:"post",
              url:"/updateCarts",
              data:{'id':id, 'num':num},
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              },
              success:function(res) {
                  data = JSON.parse(res)

                  if(data.code==200){
                      layer.msg(data.msg);
                  }else {
                      layer.msg(data.msg, {icon: 2, time: 1500}, );
                  }
              },
              error:function(data) {
                  console.log('err');
              }
          });
      }
      for(var i = 0; i < uls.length;i++){
        uls[i].onclick = function(e){
          e = e || window.event;
          var el = e.srcElement;
          var cls = el.className;
          var input = this.getElementsByClassName('Quantity-input')[0];
          var less = this.getElementsByClassName('less')[0];
          var val = parseInt(input.value);
          var that = this;
          switch(cls){
            case 'add layui-btn':
              input.value = val + 1;
              getSubTotal(this)
              var id = $(that).find(".CheckBoxShop").attr('data-id');
              var num = input.value;
              updateCars(id,num);
              break;
            case 'less layui-btn':
              if(val > 1){
                input.value = val - 1;
              }
              getSubTotal(this)
                var id = $(that).find(".CheckBoxShop").attr('data-id');
                var num = input.value;
                updateCars(id,num);
              break;
            case 'dele-btn':
              layer.confirm('你确定要删除吗',{
                yes:function(index,layero){
                    var id = $(that).find(".CheckBoxShop").attr('data-id');
                  layer.close(index)

                    $.ajax({
                        type:"post",
                        url:"/delCarts",
                        data:{'id':id},
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success:function(res) {
                            data = JSON.parse(res)

                            if(data.code==200){
                                that.parentNode.removeChild(that);
                                layer.msg(data.msg, {icon: 1, time: 1500}, );
                            }else {
                                layer.msg(data.msg, {icon: 2, time: 1500}, );
                            }
                        },
                        error:function(data) {
                            console.log('err');
                        }
                    });


                }
              })
              break;
          }
          getTotal()
        }
      }
      batchdeletion.onclick = function(){
        if(SelectedPieces.innerHTML != 0){
          layer.confirm('你确定要删除吗',{
            yes:function(index,layero){
              layer.close(index)
              for(var i = 0;i < uls.length;i++){
                var input = uls[i].getElementsByTagName('input')[0];
                if(input.checked){
                  uls[i].parentNode.removeChild(uls[i]); 
                  i--;
                }
              }
              getTotal() 
            }

          })
        }else{
          layer.msg('请选择商品')
        }
        
      }
        checkAll[0].checked = true;
        checkAll[0].onclick();
  	  }  	

  }


  exports('car',car)
}); 